package com.tamartech.greendb.dao;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class DAO
{
    private Transaction currentTransaction = null;
    
    protected DAO ()
    {
    }

    public static Session getSession ()
    {
        Session session = (Session) DAO.session.get();
        if (session == null)
        {
            session = sessionFactory.openSession();
            DAO.session.set(session);
        }
        return session;
    }

    protected void begin ()
    {
        currentTransaction = null;
        
        Transaction t = getSession().getTransaction();  
        
        log.debug ("t: " + t + (t == null ? "" : ". t.isActive(): " + t.isActive()));
        // check if there is already a transaction in progress
        if (t == null || !t.isActive())
            currentTransaction = getSession().beginTransaction();
    }

    protected void commit ()
    {
        // only commit if the transaction is ours
        if (currentTransaction != null)
            currentTransaction.commit();
//        getSession().getTransaction().commit();
    }

    protected void rollback ()
    {
        // only rollback here if the transaction is ours - I think - may want to revisit
        if (currentTransaction != null)
        {
            try
            {
                currentTransaction.rollback();
//                getSession().getTransaction().rollback();
            }
            catch (HibernateException e)
            {
                log.warn("Cannot rollback", e);
            }
    
            try
            {
                getSession().close();
            }
            catch (HibernateException e)
            {
                log.warn("Cannot close", e);
            }
            DAO.session.set(null);
        }
    }

    public static void close ()
    {
        getSession().close();
        DAO.session.set(null);
    }

    public static void resetSession()
    {
        DAO.session.set(null);
    }
    
    private static Logger log = Logger.getLogger(DAO.class);

    private static final ThreadLocal session = new ThreadLocal();

    private static final SessionFactory sessionFactory = new AnnotationConfiguration().configure()
            .buildSessionFactory();
}
